package com.huang.wangpan.strategy.process;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huang.wangpan.dto.FileIm;
import com.huang.wangpan.dao.UserFileDao;
import com.huang.wangpan.dao.UserDao;
import com.huang.wangpan.vo.UserFile;
import com.huang.wangpan.utils.CommonUtils;
import com.huang.wangpan.utils.PathAnalysis;
import com.huang.wangpan.utils.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: liminghui
 * @Date: 2020/11/7 12:37
 * @Version:
 * @Description:
 */
@Component
public class GetSubProcess implements CommonProcess {

    @Autowired
    UserFileDao userFileDao;
    @Autowired
    UserDao userDao;

    private static final Logger logger = LoggerFactory.getLogger(GetSubProcess.class);

    @Override
    public void process(String method, HttpServletRequest request, HttpServletResponse response) {
        logger.info("GetSubProcess-->process 获取下一级开始......");
        ResultData rd = new ResultData();
        String filename = request.getParameter("filename");
        String currentpath = request.getParameter("currentpath");
        String Catalogue = request.getParameter("Catalogue");
        int page = Integer.parseInt(Catalogue);
        String newpath = "";
        logger.info("currentpath= {}", currentpath);
        if (currentpath != null) {
            newpath = currentpath + filename + "/";
        } else {
            newpath = "/" + filename + "/";
        }
        PathAnalysis pa = new PathAnalysis();

        String token = CommonUtils.loadToken(request);
        String name = userDao.selectNameByToken(token);
        List<UserFile> ufs = userFileDao.searchByName(name);
        List<FileIm> fms = pa.getSubdirectories(ufs, newpath, page);
        JSONObject message = new JSONObject();
        JSONArray data = new JSONArray();
        for (FileIm temp : fms) {
            JSONObject tempj = new JSONObject();
            tempj.put("filesize", temp.getFilesize());
            tempj.put("filename", temp.getFilename());
            tempj.put("date", temp.getMtime());
            tempj.put("iconsign", temp.getIconsign());
            data.add(tempj);
        }
        JSONObject msg = new JSONObject();
        msg.put("Catalogue", page + 1);
        msg.put("currentpath", newpath);
        message.put("code", 0);
        message.put("msg", msg);
        message.put("data", data);
        rd.setData(message);
        rd.writeToResponse(response);
        logger.info("GetSubProcess-->process 更新完毕！");
    }
}
